package design.mode.model.proxy.cglibproxy.factory;


import design.mode.model.proxy.TranStation;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author ldanniel
 * @description CGLIB获取 代理类对象（TranStation）
 * @date 2023/23/13:46
 * @since jdk11
 */
public class CglibProxyFactory implements MethodInterceptor {
    private TranStation tranStation = new TranStation();

    public TranStation getProxyObject() {
        //创建enhancer,类似jdk动态代理的proxy对象
        Enhancer enhancer = new Enhancer();
        //设置父类(TranStation)的字节码对象
        enhancer.setSuperclass(TranStation.class);
        //设置回调函数 :即：MethodInterceptor 的 intercept 方法,入参是MethodInterceptor子实现类的对象
        //即：intercept()方法返回的对象
        enhancer.setCallback(this);
        return (TranStation) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        //需要调用目标对象的方法
        Object invoke = method.invoke(tranStation, objects);
        System.out.println("代理售票点，售卖火车票，并收取手续费....." + invoke);
        return invoke;
    }
}
